package cn.com.csg.smartenergy.mqtt;

//import cn.com.csg.smartenergy.modules.biz.iot.service.IotDeviceService;
//import cn.com.csg.smartenergy.modules.biz.service.PowerDeviceOnlineService;
//import cn.com.csg.smartenergy.modules.biz.service.RedisService;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Mqtt 客户端
 *
 * retained 作用：
 * 发布消息时把retain设置为true，即为保留信息。
 * 1个Topic只有唯一的retain消息，Broker会保存每个Topic的最后一条retain消息。
 * 如果需要删除retain消息，可以发布一个空的retain消息，因为每个新的retain消息都会覆盖最后一个retain消息。
 * 如果订阅者发布消息时，订阅者没有跟Broker连接成功，可以通过retain消息让订阅者在下次成功连接时一次性接收所有的内容
 *
 * qos 服务质量等级 0：almost once 1: at least once 2: exactly once
 * publish 和 subscribe 都可以指定qos，如果两者不同时，取两者最小的。例如: pub qos=0 sub qos=2 实际qos=0
 * @author ysguo
 * @date 2019-07-24
 */
@Slf4j
@Getter
@Setter
@Component
// 用于控制bean的加载顺序
@DependsOn("mqttConfig")
public class DeviceMqttOnlineClient extends AbstractMqttClient {

//    @Autowired
//    private IotDeviceService deviceService;
//
//    @Autowired
//    private PowerDeviceOnlineService deviceOnlineService;
//
//    @Autowired
//    private RedisService redisService;
//
//    @Autowired
//    private DeviceOnlineHandler onlineService;

    /**
     * 缓存设备ID
     */
    public static ConcurrentHashMap<String, Long> DEVICE_IDS = new ConcurrentHashMap<>();

    /**
     * 缓存设备最后一次的心跳时间戳
     */
    public static ConcurrentHashMap<String, Long> LAST_BEAT_TIME = new ConcurrentHashMap<>();

    @Autowired
    private DeviceOnlineCallBack callback;

    @Value("${real.time.data.prefix}")
    private String prefix;

    /**
     * 需要订阅设备的Topics
     * APP上线通知topic: @app/notify/event/gwTerminal/status/@manufacturerId/@manufacturerName/@deviceType/@model/@protocolType/@nodeId
     * 系统建立连接topic: $SYS/brokers/+/CLIENTS/+/+
     */
    @PostConstruct
    private void init() throws Exception {
        System.out.println("DeviceMqttOnlineClient init");
        // 为了防止ClientID重复
        String id = UUID.randomUUID().toString().substring(0, 8);
        this.connect(prefix + "_data_" + id, callback);
        callback.setClient(this);
        // 监听客户端上下线
        //client.subscribe("$SYS/brokers/+/CLIENTS/+/+", 1);

//        client.subscribe("+/notify/event/gwTerminal/status/#", 1);
//        this.subTopics.add("$SYS/brokers/+/CLIENTS/+/+");
//        this.subTopics.add("+/notify/event/gwTerminal/status/#");


//        this.onlineService.handleOnlineQueue();

    }

}
